// ==UserScript==
// @name        Fluid Twitter Search
// @namespace   http://fluidapp.com
// @description Simpler interface, auto-refresh, growl notifications and dock badge updates
// @include     *search.twitter.com*
// @author      Jeff Van Campen
// ==/UserScript==

(function() {
    if (window.fluid) {

        FluidTwitterSearch = Class.create();
        FluidTwitterSearch.prototype = {
            /**
             * @constructor
             */
            initialize: function() {
                /**
                 * The rate (in milliseconds) at which to check for new results
                 * @type Number
                 */
                this.reload_rate = 500;

                /**
                 * A global to keep track of timer ids
                 * @type Number
                 */
                this.timer_id = 0;

                /**
                 * Whether or not to hide the Twitter Search sidebar
                 * @type Boolean
                 */
                this.hide_sidebar = true;

                /**
                 * Whether or not to hide the Twitter Search sidebar
                 * @type Boolean
                 */
                this.hide_advanced_search_link = true;

                /**
                 * Whether or not to update the dock badge with the 
                 * number of new results
                 * @type Boolean
                 */
                this.update_dock_badge = true;

                /**
                 * Whether or not to send Growl notifications
                 * @type Boolean
                 */
                this.send_growl_notifications = true;

                /**
                 * CSS to insert
                 * @type String
                 */
                this.css  = '';
                
                /**
                 * Last result count
                 * @type Number
                 */
                this.last_result_count  = 0;

                /**
                 * Whether or not the window has focus
                 * @type Boolean
                 */
                this.window_has_focus  = 1;
             },

            /**
             * When we have new results, reload the page if the window
             * has focus.  If not, update the dock badge and send a
             * Growl notification.
             */
            onNewResults: function() {
                new_results = this.getResultCount();
                if (new_results > 0) {
                    if (this.window_has_focus) {
                        this.reload();
                    } else if (new_results != this.last_result_count){
                        if (this.update_dock_badge) {
                            window.fluid.dockBadge = new_results.toString();
                        }
                        if (this.send_growl_notifications) {
                            this.displayGrowlNotification(new_results);
                        }
                        this.last_result_count = new_results;
                    }
                }
                this.timer_id = setTimeout(function() {fts.onNewResults()}, fts.reload_rate);
            },//end onNewResults()

            /**
             * Reload the page if we have new results
             */
            reload: function() {
                new_results = this.getResultCount();
                if (new_results > 0) {
                    new_results = parseInt(new_results)
                    url = window.location.href + '&rescount=' + new_results;
                    window.location.href  = url;
                }
            },//end onNewResults()

            /**
             * When the window has focus, update window_has_focus and reload
             */
            onFocus: function() {
                this.window_has_focus = true;
                this.reload();
            },//end onFocus()

            /**
             * When the window blurs, update window_has_focus
             */
            onBlur: function() {
                this.window_has_focus = false;
            },//end onFocus()

            /**
             * Display a Growl notification
             * @param {Number} new_results
             */
            displayGrowlNotification: function(new_results) {
                var growl_title = 'Twitter Search';
                // if we know the term, include it in the notification
                if ($('searchBox').value) {
                    var growl_term  = ' for "' + $('searchBox').value + '"';
                } else {
                    var growl_term = '';
                }
                // old skool stemming
                if (new_results == 1) {
                    res_word = 'result';
                } else {
                    res_word = 'results';   
                }
                // bung it all together
                var growl_body = new_results + ' more ' + res_word + ' since you started searching' + growl_term + '.';
                window.fluid.showGrowlNotification({
                    title: growl_title,
                    description: growl_body,
                    onclick: growlCallback
                });
            },//end displayGrowlNotification()

            /** 
             * Get a count of new search results
             * @return {Number} the number of new search results
             */
            getResultCount: function () {
                //alert($('new-res-count').innerHTML);
                if (!$('new-res-count')) {
                    window.console.log('Result Count (#new-res-count) not found.');
                    return 0;
                } else {
                    return $('new-res-count').innerHTML;
                }
            },//end getResultCount()

            /**
             * Inserts CSS, according to config settings
             */
            insertCss: function() {
                 if (this.hide_sidebar) {
                     this.css += '#sidebar {display: none !important}';
                     this.css += '#mainContent,#headerContent{width: 612px !important;}';
                 }
                 if (this.hide_advanced_search_link) {
                     this.css += '#searchOptionsCtrl {display: none !important}'
                 }
                 if (this.css != '') {
                     var s = new Element('style', { type: 'text/css' });
                     // grr Element.update() isn't working?
                     s.appendChild(document.createTextNode(this.css));
                     if ($$('head').length != 1) {
                         window.console.log('Head tag error.  Not sure where to insert styles.');
                     } else {
                         $$('head')[0].appendChild(s);
                     }
                 }
            }//end insertCss()
        }//end FluidTwitterSearch.prototype

        /**
         * Give the window focus when the user clicks a Growl notification
         */
        function growlCallback() {
            window.fluid.activate();
        }

        // It all happens here
        fts = new FluidTwitterSearch();
        Event.observe(window, 'blur', function() { fts.onBlur(); });
        Event.observe(window, 'focus', function() { fts.onFocus(); });
        fts.insertCss();
        fts.timer_id = setTimeout(function() { fts.onNewResults()  },fts.reload_rate);
    }//end if (window.fluid)
})();